package com.sky.agent.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sky.agent.entity.UmcAppDeviceToken;
import com.sky.agent.entity.UmcAppPushMsg;
import com.sky.agent.service.AppService;
import com.sky.agent.utils.OkHttp3Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AppServiceImpl implements AppService {


    @Value("${message.ios.pushUrl:api.push.apple.com}")
    private String iosMessagePushUrl;

    @Value("${message.ios.apnKeyPath:/opt/appProxy/AuthKey_F36U2J9D9T.p8}")
    private String apnKeyPath;

    @Value("${message.ios.saveDeviceTokenUrl:https://127.0.0.1:9344/sky_hrm_20250711/app/saveDeviceToken}")
    private String saveDeviceTokenUrl;

    @Value("${message.ios.queryDeviceTokenUrl:https://127.0.0.1:9344/sky_hrm_20250711/app/queryDeviceToken}")
    private String queryDeviceTokenUrl;
    @Resource
    private IosPushMsgService iosPushMsgService;

    @Override
    public Map saveDeviceToken(UmcAppDeviceToken appDeviceToken) {
        Map<String, Object> map = new HashMap<>();
        try {
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("account", appDeviceToken.getAccount());
            paramsMap.put("deviceToken", appDeviceToken.getDeviceToken());
            okhttp3.Response response = OkHttp3Util.doPost(saveDeviceTokenUrl, paramsMap, 5000, 3);
            String result = response.body().string();
            if (StringUtils.isNotBlank(result)) {
                JSONObject resultJson = JSONObject.parseObject(result);
                map.put("code", "0000");
                map.put("message", resultJson.getString("message"));
            } else {
                map.put("code", "0001");
                map.put("message", "保存失败！");
            }
        } catch (IOException e) {
            log.error("Exception : {}", e);
            map.put("code", "500");
            map.put("message", "系统异常，请联系管理员！");
        }
        return map;
    }

    @Override
    public Map pushMsg(UmcAppPushMsg appPushMsg) {
        Map<String, Object> map = new HashMap<>();
        try {
            String result = null;
            iosPushMsgService.init(apnKeyPath, iosMessagePushUrl);


            Map<String, String> headMap = new HashMap<>();
            headMap.put("content-type", "application/json");
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("str", JSONObject.toJSONString(appPushMsg.getReceiveAccountList()));
            okhttp3.Response response = OkHttp3Util.doPost(queryDeviceTokenUrl, paramsMap, 5000, 3);
//            okhttp3.Response response = OkHttp3Util.doPostJSON(queryDeviceTokenUrl, paramsMap, 5000, 3);
            String responseResult = response.body().string();
            if (StringUtils.isBlank(responseResult)) {
                map.put("code", "0001");
                map.put("message", "未查询到设备token");
                return map;
            }

            JSONObject jsonObject = JSON.parseObject(responseResult);
            if (jsonObject.containsKey("data")) {
                List list = jsonObject.getJSONArray("data");
                if (CollectionUtil.isEmpty(list)) {
                    map.put("code", "0001");
                    map.put("message", "未查询到设备token");
                    return map;
                }
            }
            List list = jsonObject.getJSONArray("data");
            for (Object obj : list) {
                String tokenStr = (String) obj;
                if (StringUtils.isNotBlank(appPushMsg.getContext())) {
                    result = iosPushMsgService.sendPushNotification(tokenStr, StringUtils.isNotBlank(appPushMsg.getTitle()) ? appPushMsg.getTitle() : appPushMsg.getSendAccountName(), appPushMsg.getSendAccountName() + "-" + appPushMsg.getContext());
                } else {
                    // 发送通知
                    result = iosPushMsgService.sendPushNotification(tokenStr, StringUtils.isNotBlank(appPushMsg.getTitle()) ? appPushMsg.getTitle() : appPushMsg.getSendAccountName(), appPushMsg.getSendAccountName() + "发来新的消息，敬请查看！");
                }
                log.info("用户ucuid:{},推送结果: {}", tokenStr, StringUtils.isBlank(result) ? "推送成功" : result);
            }
            if (StringUtils.isNotBlank(result)) {
                map.put("code", "0002");
                map.put("message", result);
            } else {
                map.put("code", "0000");
                map.put("message", "消息推送成功！");
            }
        } catch (Exception e) {
            log.error("Exception :{}", e);
            map.put("code", "500");
            map.put("message", "消息推送异常！");
        } finally {
            // 服务停止时关闭客户端
            iosPushMsgService.close();
        }
        return map;
    }
}
